import { request } from "../../request/index"
Page({
    data: {
        goodsObj: {},
        isCollect:false /// 是否收藏
    },
    GoodsInfo: {}, //商品对象
    onShow: function () {
        /// 返回的是一个数组，第一项是首页，最后一项是当前页面
        let pages = getCurrentPages();
        let currentPage = pages[pages.length - 1];/// 当前页
        let options = currentPage.options;
        const { goods_id } = options;
        this.getGoodsDetail(goods_id)
    },
    async getGoodsDetail(goods_id) {
        const goodsObj = await request({
            url: '/goods/detail',
            data: {
                goods_id
            }
        })
        this.GoodsInfo = goodsObj;
        console.log(this.GoodsInfo);
        let collect=wx.getStorageSync('collect')||[]
        let isCollect=collect.some(v=>{
            /// 判断商品是否收藏
            return v.goods_id===this.GoodsInfo.goods_id
        })
        this.setData({
            goodsObj: {
                goods_name: goodsObj.goods_name,
                goods_price: goodsObj.goods_price,
                goods_introduce: goodsObj.goods_introduce.replace(/\.webp/g, '.jpg'),
                pics: goodsObj.pics
            },
            isCollect
        })
    },
    /// 图片预览
    handlePreviewImg(e){
       const urls=this.GoodsInfo.pics.map(v=>v.pics_mid)
       const current = e.currentTarget.dataset.url
       wx.previewImage({
           current,
           urls
       })
    },
    /// 加入购物车
    handleAddCart(){
        let cart = wx.getStorageSync("cart") || [];
        let index = cart.findIndex(v => v.goods_id === this.GoodsInfo.goods_id);
        if (index === -1) {
            this.GoodsInfo.num = 1;
            this.GoodsInfo.checked = true;
            cart.push(this.GoodsInfo)
        } else {
            cart[index].num++;
        }
        wx.setStorageSync("cart", cart);
        wx.showToast({
            title: '加入成功',
            mask: true
        })
    },
    /// 商品收藏
    handleGoodsCollect(){
        let isCollect=false
        let collect=wx.getStorageSync('collect')||[]
        let index=collect.findIndex(v=>v.goods_id===this.GoodsInfo.goods_id)
        if(index!==-1){
            /// 已经收藏过了
            collect.splice(index,1)
            isCollect=false
            wx.showToast({
                title:"取消成功",
                mask:true
            })
        }else{
            collect.push(this.GoodsInfo)
            isCollect=true
            wx.showToast({
                title:'收藏成功',
                mask:true
            })
        }
        wx.setStorageSync("collect", collect);
        this.setData({
            isCollect
        })
    }
})
